import { memo, useEffect, useState, useRef } from 'react'
import './index.css'
import Model from '../Model/index'
import Config from '../Config';
import IncreaseItem from '../IncreaseItem';
const { electron: { ipcRenderer: ipc } } = window;
const Body = () => {
  const [message, setMessage] = useState(-1)
  const [box1, setBox1] = useState([])
  const [box2, setBox2] = useState([]);
  const [num, setNum] = useState(-1);
  const [show, setShow] = useState(false);
  const [inputValue, setInputValue] = useState('')
  const [editRowIndex, setEditRowIndex] = useState(-1)
  const [editColIndex, setEditColIndex] = useState(-1)
  const [currentRow, setCurrentRow] = useState(-1)
  const [increase, setIncrease] = useState(false)
  const [showTip, setShowTip] = useState(false)
  const [incData, setIncData] = useState(false)
  const preDeleteIndex = useRef(-1)
  const currentKeys = useRef([])
  useEffect(() => {
    ipc.on('data-base-name', (event, arg) => {
      currentKeys.current = []
      setBox1(arg)
      setBox2([])
      setNum(-1)
    })
    ipc.on('open-table-response', (event, arg) => {
      currentKeys.current = Object.keys(arg[0])
      if (arg[0]['id'] === 'lst-dd') {
        arg.splice(0, 1)
      }
      setBox2(arg)
    })
  }, [])
  const onSelect = (i) => {
    if (num === i) {
      return
    }
    const { name } = box1[i]
    setNum(i)
    setEditColIndex(-1)
    setEditRowIndex(-1)
    setCurrentRow(-1)
    ipc.send('open-table-request', name)
  }
  // 删除表格
  const onDeleteTable = (i) => {
    preDeleteIndex.current = i;
    setShow(true)
    setMessage(1)
  }
  const onConfirm = () => {
    if (message) {
      const { name } = box1[preDeleteIndex.current];
      ipc.send('delete-table-request', name)
      const i = preDeleteIndex.current
      box1.splice(i, 1)
      if (num > i && box1.length) {
        setNum(num - 1);
      } else if (num < i && box1.length) {

      } else {
        currentKeys.current = []
        setNum(-1)
        setBox2([])
        setCurrentRow(-1)
      }
    } else {
      ipc.send('delete-data-item-requset', {
        table: box1[num]['name'],
        id: box2[currentRow]['id'],
      })
      setCurrentRow(-1)
      box2.splice(currentRow, 1)
    }
    setShow(false)

  }
  const onCancel = () => {
    setShow(false)
  }
  // 根据点击事件判断是否将当前单元设置为可编辑
  const onEditItem = (i, j, value) => {
    setEditRowIndex(i)
    setEditColIndex(j)
    setInputValue(value)
    j === 0 && setCurrentRow(i)
  }
  // 改变输入框的输入
  const onChangeInput = (e) => {
    const { target: { value } } = e
    setInputValue(value)
  }
  // 监听输入框的Enter按键,改变当前展示为最新展示
  const onInputKeyDown = (row, col, e) => {
    if (e.keyCode === 13) {
      const keysArray = Object.keys(box2[row])
      box2[row][keysArray[col]] = inputValue
      setEditRowIndex(-1)
      setEditColIndex(-1)
      ipc.send('edit-table-item', {
        id: box2[row]['id'],
        table: box1[num]['name'],
        selectedKey: keysArray[col],
        selectedValue: inputValue
      })
    }
  }
  // 选择当前单元的展示方式（只展示｜可编辑）
  const isInput = (items, item, indexs, index) => {
    if (indexs === editRowIndex && index === editColIndex && index !== 0) {
      return (
        <input
          key={index}
          value={inputValue}
          className="box2-content-input"
          type="text"
          onKeyDown={onInputKeyDown.bind(this, indexs, index)}
          onChange={onChangeInput} />
      )
    } else {
      return (
        <div className="box2-content-title"
          onClick={onEditItem.bind(this, indexs, index, items[item])}
          key={index}>
          {items[item]}
        </div>
      )
    }
  }
  // 提交增加新的数据项
  const onIncreaseItem = (itemsObj, itemsArray) => {
    if (currentKeys.current.length !== itemsArray.length) {
      setShowTip(true)
      setTimeout(() => {
        setShowTip(false)
      }, 800)
      return
    }
    box2.push(itemsObj)
    ipc.send('increase-item', {
      table: box1[num]['name'],
      items: itemsArray
    })
    setIncrease(false)
  }
  // 删除所选定的数据项
  const onDeleteDataItem = () => {
    if (currentRow === -1) {
      return
    }
    setMessage(0)
    setShow(true)
  }
  // 弹出新增项的填写窗口
  const onIncrease = () => {
    setIncrease(true)
  }
  // 关闭弹出窗口
  const onIncreaseCancel = () => {
    setIncrease(false)
  }
  // 提交新增数据库的数据
  const onIncreaseDataSheet = (state, onVerify) => {
    let flag = true;
    const obj = {}
    const stateArray = Object.keys(state);
    for (let temp of stateArray) {
      if (!state[temp]) {
        obj[temp] = ''
      }
      flag &= !!state[temp]
    }
    if (!flag) {
      onVerify.call(this, obj)
      return
    }
    ipc.send('inc-data-requset', state)
    box1.push({ name: state['sheetName'] })
    setIncData(false)
  }
  // 关闭新增数据库的窗口
  const onCancelDataSheet = () => {
    setIncData(false)
  }
  // 打开新增数据表的窗口
  const onOpenIncData = () => {
    setIncData(true)
  }
  return (
    <>
      {incData && <Config onIncreaseDataSheet={onIncreaseDataSheet} onCancel={onCancelDataSheet}></Config>}
      {increase && <IncreaseItem items={currentKeys.current} onClick={onIncreaseItem} onCancel={onIncreaseCancel}></IncreaseItem>}
      <Model type="error" message={'请填写所有字段'} isShow={showTip}></Model>
      <Model message={message ? '确认是否删除该表?' : '确认是否删除该项数据?'} type="selected" isShow={show} onConfirm={onConfirm} onCancel={onCancel}></Model>
      <div className="body-container">
        <div className="body-box1">
          <div className="body-box1-title">
            数据库列表
            <div className="body-box1-symbol" onClick={onOpenIncData}></div>
          </div>
          <div className="body-box1-content">
            {box1.map((item, index) => {
              const { name } = item
              return (
                <div key={index} className={num === index ? 'box1-name-field box1-name-selected' : 'box1-name-field'}>
                  <div className="box1-name-title" onClick={onSelect.bind(this, index)}>
                    {name}
                  </div>
                  <div className="box1-name-delete" onClick={onDeleteTable.bind(this, index)}>
                    删除
                  </div>
                </div>
              )
            })}
          </div>
        </div>
        <div className="body-box2">
          <div className="body-box2-title">
            表内详情
            <div>
              <div className="box2-button"
                style={box1.length ? { backgroundColor: 'orange', marginRight: '10px' } : { display: 'none' }}
                onClick={onIncrease}>新增</div>
              <div style={currentRow !== -1 ? {} : { display: 'none' }}
                className="box2-button"
                onClick={onDeleteDataItem}>删除</div>
            </div>
          </div>
          <div className="body-box2-content">
            <div className="box2-content-titles">
              {currentKeys.current.map((item, index) => (
                <div className="box2-content-title" key={index}>
                  {item}
                </div>
              ))}
            </div><br />
            <div className="box2-content-field">
              {
                box2.map((items, indexs) => (
                  <>
                    <div key={indexs} className={currentRow === indexs ?
                      'box2-content-titles box2-content-selected-name' :
                      "box2-content-titles box2-content-font-size"}>
                      {
                        Object.keys(items).map((item, index) => {
                          return isInput(items, item, indexs, index)
                        })
                      }
                    </div><br />
                  </>
                ))
              }
            </div>
          </div>
        </div>
      </div>
    </>
  )
}
export default memo(Body)